package com.umessage.hotel.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.MataData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.DefaultFastFileStorageClient;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.umessage.common.controller.BaseController;
import com.umessage.common.domain.ResponseBo;
import com.umessage.system.domain.User;

import net.coobird.thumbnailator.Thumbnails;


/**
 * 上传图片  
 * @author xjh
 *
 */
@Controller
public class UploadController extends BaseController {
	
/**
 * 	前台判断——格式：png/jpg    
 *	
 */
	@Autowired
	FastFileStorageClient fastFileStorageClient;
	//上传单张图片
	@RequestMapping(value = "upload/uploadPic")
	public @ResponseBody 
	ResponseBo uploadPic(@RequestParam(required = false) MultipartFile file
			,HttpServletRequest request,String typePic,String fid) throws IOException, Exception{
			//校验单张图片格式大小及图片宽高
			String filepath=file.getOriginalFilename();
			String suffix = filepath.substring(filepath.lastIndexOf('.'));
	    	if(".jpg".equals(suffix)||".png".equals(suffix)||".JPG".equals(suffix)||".PNG".equals(suffix)) {
	    		String filePath = request.getSession().getServletContext().getRealPath("/upload/")+ file.getOriginalFilename();
	    		File saveFile = new File(filePath);
                if (!saveFile.getParentFile().exists()) {
                	saveFile.getParentFile().mkdirs();
                }
                // 转存文件
                file.transferTo(saveFile);
                List<File> filelist=new ArrayList<>();
                filelist.add(saveFile);
	    		BufferedImage bufferedImg = ImageIO.read(saveFile);
				int imgWidth = bufferedImg.getWidth();
				int imgHeight = bufferedImg.getHeight();
				System.out.println("imgWidth============="+imgWidth);
				System.out.println("imgHeight============="+imgHeight);
				//房间列表150*150
    			if(imgWidth<150||imgHeight<150) {
    				return ResponseBo.warn("图片的像素必须大于150*150");
    			}
	    		User user = super.getCurrentUser();	
				//List集合 保存一堆url 
				List<String> list = new ArrayList<String>();
				ResponseBo rb=null;
                // 保存文件
                rb=saveFile(request, filelist, list,typePic,fid,user.getHotelId());
                return rb;
	    	}else {
	    		return ResponseBo.warn("图片格式不对，请重新上传jpg或png格式的图片");
	    	}
	}
	//上传多张图片
	@RequestMapping(value = "upload/uploadPics")
	public @ResponseBody 
	ResponseBo uploadPics(@RequestParam(required = false) MultipartFile[] files
			,HttpServletRequest request,String typePic,String fid) throws IOException, Exception{
		ResponseBo rb=null;
		if (files != null && files.length > 0) {
			List<File> filelist=new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String filepath=file.getOriginalFilename();
    			String suffix = filepath.substring(filepath.lastIndexOf('.'));
            	if(".jpg".equals(suffix)||".png".equals(suffix)||".JPG".equals(suffix)||".PNG".equals(suffix)) {
            		String filePath = request.getSession().getServletContext().getRealPath("/upload/")+ file.getOriginalFilename();
    	    		File saveFile = new File(filePath);
                    if (!saveFile.getParentFile().exists()) {
                    	saveFile.getParentFile().mkdirs();
                    }
                    // 转存文件
                    file.transferTo(saveFile);
                    filelist.add(saveFile);
    	    		BufferedImage bufferedImg = ImageIO.read(saveFile);
    				int imgWidth = bufferedImg.getWidth();
    				int imgHeight = bufferedImg.getHeight();
    				System.out.println("imgWidth============="+imgWidth);
    				System.out.println("imgHeight============="+imgHeight);
    				//首页banner 750*400
        			if(imgWidth<750||imgHeight<400) {
        				return ResponseBo.warn("图片的像素必须大于750*400");
        			}
            	}else {
                	return ResponseBo.warn("图片格式不对，请重新上传jpg或png格式的图片");
	            }
            }
		//List集合 保存一堆url 
		User user = super.getCurrentUser();
		List<String> list = new ArrayList<String>();
	        if (files != null && files.length > 0) {
	            for (int i = 0; i < files.length; i++) {
	                MultipartFile file = files[i];
	                // 保存文件
	                rb=saveFile(request, filelist, list,typePic,fid,user.getHotelId());
	            }
	        }
	        }
	        return rb; 
	}
	 @SuppressWarnings("unchecked")
	private ResponseBo saveFile(HttpServletRequest request,
			 List<File> filelist, List<String> list,String typePic,String fid,String hotelId) {
		 // 判断文件是否为空
	        if (!filelist.isEmpty()) {
	        	for (File saveDir : filelist) {
	        		//request.getSession().getServletContext().getRealPath("/")+
		        	String filePath = request.getSession().getServletContext().getRealPath("/upload/")+ saveDir.getName();//file.getOriginalFilename();
		        	String suffix = filePath.substring(filePath.lastIndexOf('.'));
			        	String uuidPicName=UUID.randomUUID().toString() + suffix;
			        	//上传图片路径
			        	String newPicPath="";
			        	String picSrc="";
			        	if("hotelBanner".equals(typePic)) {
			        		 newPicPath=request.getSession().getServletContext().getRealPath("/thumbnails/")+fid+"/" +uuidPicName ;
			        		 picSrc=request.getContextPath()+"/thumbnails/"+fid+"/" +uuidPicName;
			        	}else {
			        		 newPicPath=request.getSession().getServletContext().getRealPath("/thumbnails/")+hotelId+"/"+fid+"/" +uuidPicName ;	
			        		 picSrc=request.getContextPath()+"/thumbnails/"+hotelId+"/"+fid+"/" +uuidPicName;
			        	}
		            	try {
			               /* File saveDir = new File(filePath);
			                if (!saveDir.getParentFile().exists()) {
			                    saveDir.getParentFile().mkdirs();
			                }
			                // 转存文件
			                file.transferTo();*/
			                File tbDir = new File(newPicPath);
			                if (!tbDir.getParentFile().exists()) {
			                	tbDir.getParentFile().mkdirs();
			                }
			                picThumbnails(filePath,newPicPath,typePic);
			                //文件大小
			    			String filesize=String.valueOf(tbDir.length());
			                //扩展名
			    			String ext = suffix;
			    			 // 上传   （文件上传可不填文件信息，填入null即可）
			    			InputStream inputStream=new FileInputStream(tbDir);
			    			StorePath storePath = fastFileStorageClient.uploadFile(inputStream, Long.valueOf(filesize), FilenameUtils.getExtension(tbDir.getName()), null);
			                list.add("/"+storePath.getFullPath());
			                System.out.println("newPicPath"+newPicPath);
			                System.out.println("saveDir.getPath()"+saveDir.getPath());
			                deleteFile(tbDir.getPath());
			                deleteFile(saveDir.getPath());
			                return ResponseBo.ok(list);
			            } catch (Exception e) {
			                e.printStackTrace();
			                return null;
			            }
				}
	        	
	        }
	        return null;
	    }
	 /**
	  * 缩略图
	  * @param fileName
	  * @param newPicPath
	  * @param typePic
	  */
	 public void picThumbnails(String filePath,String newPicPath,String typePic) {
		 try {
			 if("hotelBanner".equals(typePic)) {
             	//首页酒店图：750*400
             	Thumbnails.of(filePath).size(750,400).toFile(newPicPath);
             	//Thumbnails.of(filePath).scale(1f).outputQuality(0.25f).toFile(newPicPath);
             }else if("roomList".equals(typePic)) {
             	//首页列表房间图：150*150
             	Thumbnails.of(filePath).size(150,150).toFile(newPicPath);
             	//Thumbnails.of(filePath).scale(1f).outputQuality(0.25f).toFile(newPicPath);
             }else if("roomInfo".equals(typePic)){
             	//房间详情图：宽750*高398 改为详情banner 750*440
             	Thumbnails.of(filePath).size(750,400).toFile(newPicPath);
             	//Thumbnails.of(filePath).scale(1f).outputQuality(0.25f).toFile(newPicPath);
             }
		} catch (Exception e) {
			e.printStackTrace();
		}
	 }
	 /**
	     * 删除单个文件
	     *
	     * @param fileName
	     *            要删除的文件的文件名
	     * @return 单个文件删除成功返回true，否则返回false
	     */
	    public static boolean deleteFile(String fileName) {
	        File file = new File(fileName);
	        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
	        if (file.exists() && file.isFile()) {
	            if (file.delete()) {
	                System.out.println("删除单个文件" + fileName + "成功！");
	                return true;
	            } else {
	                System.out.println("删除单个文件" + fileName + "失败！");
	                return false;
	            }
	        } else {
	            System.out.println("删除单个文件失败：" + fileName + "不存在！");
	            return false;
	        }
	    }
}
